package com.zxr.demo.filter;

import com.zxr.demo.utils.JwtUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.redisson.api.RedissonClient;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

@Component
@Order(1)
public class AuthFilter implements Filter {
    private RedissonClient redissonClient;

    // 不需要认证的URL列表
    static final Set<String> whiteList = new HashSet<>();

    static {
        whiteList.add("/api/login");
        whiteList.add("/api/is_auth");
        whiteList.add("/api/add_name");
        whiteList.add("/api/register"); // 可以根据需要添加其他白名单路径
    }

    // 通过构造函数注入RedissonClient
    public AuthFilter(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    // 定义authorization变量，用于存储请求头中的认证信息
    private String authorization;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        // CORS 处理 直接放行 OPTIONS 预检请求
        if ("OPTIONS".equalsIgnoreCase(httpRequest.getMethod())) {
            chain.doFilter(httpRequest, httpResponse);
            return; // 结束处理
        }
        // 获取请求头中的Authorization信息
        authorization = httpRequest.getHeader("Authorization");
        httpResponse.setContentType("application/json;charset=UTF-8");
        String requestURI = httpRequest.getRequestURI();

        // 检查是否为白名单路径
        if (whiteList.contains(requestURI)) {
            chain.doFilter(request, response);
            return;
        }

        // 获取token（通常从Authorization头中获取）
        String token = httpRequest.getHeader("Authorization");

        if (token == null || token.isEmpty()) {
            sendErrorResponse(httpResponse, "未提供认证令牌", HttpStatus.UNAUTHORIZED);
            return;
        }

        // 通常token格式为 "Bearer <token>"，需要提取实际token
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        Object obj = redissonClient.getMapCache("auth").get(token);
        if (obj == null) {
            System.out.println("认证令牌无效或已过期");
            sendErrorResponse(httpResponse, "认证令牌无效或已过期", HttpStatus.UNAUTHORIZED);
        } else {
            request.setAttribute("token", token);
            chain.doFilter(request, response);
        }
    }

    /**
     * 验证用户是否已认证
     *
     * @param authorization 包含JWT令牌的请求头信息
     * @return 已认证返回true，否则返回false
     */
    private boolean isAuthenticated(String authorization) {
        // 验证逻辑：
        // 1. 检查Authorization头是否存在且格式正确
        // 2. 验证JWT令牌的有效性
        if (authorization == null || !authorization.startsWith("Bearer ")) {
            return false;
        }

        try {
            String token = authorization.substring(7); // 去除"Bearer "前缀
            // 调用JWT工具类验证令牌有效性
            return JwtUtil.validateToken(token);
        } catch (Exception e) {
            return false;
        }
    }

    private void sendErrorResponse(HttpServletResponse response, String message, HttpStatus status)
            throws IOException {
        response.setStatus(status.value());
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write("{\"code\":" + status.value() + ",\"message\":\"" + message + "\"}");
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化逻辑（如果需要）
    }

    @Override
    public void destroy() {
        // 清理逻辑（如果需要）
    }

}